import {
  getPresetParamsApi, //获取设备参数
  downloadPrintSoftware, //下载打印控件
  addOperateLog,
  getUserDataByAccount,
} from "@/api/common";
import { applicationQueryList } from "@/api/systemManagement/applicationManagement.js";
import { getPublicKey } from "@/api/login.js";
import { Message, MessageBox, Loading } from "element-ui";
import store from "../store";
import JSEncrypt from "./jsencrypt.min";

Array.prototype.remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

let utils = {};

/**
 * 用于页面跳转或刷新前在session中保存当前的水司、组织、身份信息
 */

utils.setCurrentInfo = function () {
  let currentInfo = store.getters.currentInfo;
  currentInfo.currDs
    ? sessionStorage.setItem("currDs", currentInfo.currDs)
    : sessionStorage.removeItem("currDs");
  currentInfo.currOrg
    ? sessionStorage.setItem("currOrg", currentInfo.currOrg)
    : sessionStorage.removeItem("currOrg");
  currentInfo.currLeader
    ? sessionStorage.setItem("currLeader", currentInfo.currLeader)
    : sessionStorage.removeItem("currLeader");
  currentInfo.currLeaderOrg
    ? sessionStorage.setItem("currLeaderOrg", currentInfo.currLeaderOrg)
    : sessionStorage.removeItem("currLeaderOrg");
};

/**
 * 用于页面跳转或刷新前在session中保存当前的水司、组织、身份信息
 */

utils.getAppList = function () {
  return new Promise((resolve, reject) => {
    applicationQueryList().then(
      (res) => {
        let arr = res.data.map((item) => {
          const obj = {
            label: item.name,
            value: item.id,
          };
          return obj;
        });
        resolve(arr);
      },
      (error) => {
        reject(error);
      }
    );
  });
};
/**
 * 用于清除当前的用户信息
 */

utils.clearUserInfo = function () {
  localStorage.removeItem("GDH_WATER_TOKEN");
  localStorage.removeItem("version");
  localStorage.removeItem("currDs");
  localStorage.removeItem("currOrg");
  localStorage.removeItem("currLeader");
  localStorage.removeItem("currLeaderOrg");
};
utils.addOperateLog = function (id, content) {
  let params = {
    businessId: id,
    content: content,
  };
  addOperateLog(params).then((res) => {});
};
/**
 * 用于账号密码验证时对密码的加密
 * @param {String} scope
 * @returns {String}
 */
utils.encryptPassword = function (val) {
  return new Promise((resolve, reject) => {
    getPublicKey().then((res) => {
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey(res.data); //设置公钥
      let rsaPassWord = encryptor.encrypt(val);
      resolve(rsaPassWord);
    });
  });
};

function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
utils.setUuid = function () {
  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
};

/**
 * 将表格中的数据拿出
 * @method
 * @param {Object} scope
 * @return {String} res
 */
utils.timeFormat = function (scope) {
  var val = scope.row[scope.column.property];
  var res = val ? utils.dealTimeTamp(val) : null;
  return res;
};

/*
 节流函数
*/
utils.throttle = function (func, wait, immediate) {
  let timer, flag;
  if (immediate) {
    if (!flag) {
      flag = true;
      typeof func === "function" && func();
      timer = setTimeout(() => {
        flag = false;
      }, wait);
    }
  } else {
    if (!flag) {
      flag = true;
      typeof func === "function" && func();
      timer = setTimeout(() => {
        flag = false;
      }, wait);
    }
  }
};

/**整理天气及预警数据，返回可在卡片显示的数据 */

utils.dealWeatherWarn = function (areaOps, areaContrast, weather, warn) {
  function formatTemp(temp) {
    if (temp == 9999) {
      temp = "";
    }
    return temp;
  }

  let tempData = weather.map((i) => {
    let arr = [];
    let area = i.position;
    let areaCode = "";

    //模糊查找，得出区域名称
    for (let key in areaContrast) {
      if (area.indexOf(key) != -1) {
        area = areaContrast[key];
      }
    }
    //跟据区域名称取匹配区域code
    areaOps.map((j) => {
      if (area.indexOf(j.label) != -1) {
        areaCode = j.value;
      }
    });

    let obj = {};
    obj.temp = formatTemp(i.temperature);
    obj.text = `${i.info}\n${formatTemp(i.minTemp)}~${formatTemp(
      i.maxTemp
    )}℃\n${i.windDirect} ${i.windPower}`;
    //找出对应的icon
    obj.icon = utils.getWeatherIcon(i.info);
    obj.warnContent = i.info;
    arr.push(obj);
    return {
      title: area + "气象",
      warnArea: areaCode,
      data: arr,
      haveWarning: false,
    };
  });
  warn.map((i) => {
    let area = i.stationName;
    let areaCode = "";
    //模糊查找，得出区域名称
    for (let key in areaContrast) {
      if (area.indexOf(key) != -1) {
        area = areaContrast[key];
      }
    }
    //跟据区域名称取匹配区域code
    areaOps.map((j) => {
      if (area.indexOf(j.label) != -1) {
        areaCode = j.value;
      }
    });
    i.warnArea = areaCode;

    //创建天气obj
    let obj = {};
    obj.temp = i.temperature;
    obj.warnType = i.warnSigName;
    obj.text = `${i.warnSigName}\n${i.createTime}`;
    obj.warnContext = i.warnContent;
    obj.warnStartTime = i.warnStartTime; //预案开始时间
    obj.warnTypeName = i.warnType; //台风
    obj.warnLevel = i.warnLevel; //颜色
    obj.warnSignalName = i.warnSigName; //暴雨黄色预警
    obj.warnSignalId = i.warnSigCode; //yellow_rain

    //找出对应的icon
    obj.icon = utils.getWeatherIcon(i.warnLevel + i.warnType);
    //比对天气数据
    tempData.map((j) => {
      if (j.warnArea === i.warnArea) {
        //若未更改状态，先初始化
        if (!j.haveWarning) {
          j.haveWarning = true;
          j.data = [];
        }
        j.data.push(obj);
      }
    });
  });
  return tempData;
};
/**跟据天气描述返回icon */
utils.getWeatherIcon = function (text) {
  let obj = {
    晴: "sum",
    云: "cloudy",
    阴: "cloudy-yt",
    小雨: "small-rain",
    大雨: "big-rain",
    风: "el-icon-wind-power",
    白色台风: "white-tf",
    蓝色台风: "blue-tf",
    黄色台风: "yellow-tf",
    橙色台风: "orange-tf",
    红色台风: "red-tf",
    蓝色暴雨: "blue-by",
    黄色暴雨: "yellow-by",
    橙色暴雨: "orange-by",
    红色暴雨: "red-by",
  };
  let icon = "";
  for (const key in obj) {
    if (text.indexOf(key) != -1) {
      icon = obj[key];
    }
  }
  return icon;
};

/**
 * 搜索栏下拉选项循环
 * @method dealOption
 * @param {Array} obj 从后台拿到的数据,type:1取值，其他取Id
 * @return {Array} arr
 */
utils.dealOption = function (obj, type) {
  var arr = new Array();
  if (obj) {
    obj.forEach(function (item, index) {
      arr.push({
        label: item.itemName,
        itemValue: item.itemCode,
        value: item.itemCode,
        name: item.itemName,
      });
    });
  }
  return arr;
};
// 返回 类似 2016-01-02 格式的字符串
utils.formatDate = function (val) {
  var y = val.getFullYear();
  var m = val.getMonth() + 1;
  var d = val.getDate();
  if (m < 10) m = "0" + m;
  if (d < 10) d = "0" + d;
  return y + "-" + m + "-" + d;
};
/**
 * 将时间戳换成可看的格式
 * */
utils.TimeFormat = function (obj, type) {
  if (obj) {
    if (!utils.isNumber(obj)) {
      return obj;
    }
    var time = new Date(obj);
    var y = time.getFullYear();
    var M = time.getMonth() + 1;
    M < 10 ? (M = "0" + M) : null;
    var d = time.getDate();
    d < 10 ? (d = "0" + d) : null;
    var h = time.getHours();
    h < 10 ? (h = "0" + h) : null;
    var m = time.getMinutes();
    m < 10 ? (m = "0" + m) : null;
    var s = time.getSeconds();
    s < 10 ? (s = "0" + s) : null;
    if (type === 1) {
      return y + "-" + M + "-" + d;
    } else if (type === 2) {
      return h + ":" + m;
    } else if (type === 3) {
      return y + "-" + M + "-" + d + " " + h + ":" + m;
    } else {
      return y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;
    }
  } else {
    return "";
  }
};

/**
 * 字符串日期转换为时间戳
 * */
utils.stringFormatTime = function (obj) {
  if (obj) {
    let date = new Date(obj.replace(/-/g, "/"));
    let time = date.getTime() / 1000;
    return time;
  }
};

// 获取一个月的日期范围
// this.getMonth(type,months)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，months为数字类型，0代表本月，-1代表上月，1代表下月
utils.getMonth = function (type, months) {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  if (Math.abs(months) > 12) {
    months = months % 12;
  }
  if (months != 0) {
    if (month + months > 12) {
      year++;
      month = (month + months) % 12;
    } else if (month + months < 1) {
      year--;
      month = 12 + month + months;
    } else {
      month = month + months;
    }
  }
  month = month < 10 ? "0" + month : month;
  var date = d.getDate();
  var firstday = year + "-" + month + "-" + "01";
  var lastday = "";
  if (
    month == "01" ||
    month == "03" ||
    month == "05" ||
    month == "07" ||
    month == "08" ||
    month == "10" ||
    month == "12"
  ) {
    lastday = year + "-" + month + "-" + 31;
  } else if (month == "02") {
    if (
      (year % 4 == 0 && year % 100 != 0) ||
      (year % 100 == 0 && year % 400 == 0)
    ) {
      lastday = year + "-" + month + "-" + 29;
    } else {
      lastday = year + "-" + month + "-" + 28;
    }
  } else {
    lastday = year + "-" + month + "-" + 30;
  }
  var day = "";
  if (type == "s") {
    day = firstday;
  } else {
    day = lastday;
  }
  return day;
};

//获取当前时间
utils.getCurrentDate = function (type) {
  var time = new Date();
  var y = time.getFullYear();
  var M = time.getMonth() + 1;
  M < 10 ? (M = "0" + M) : null;
  var d = time.getDate();
  d < 10 ? (d = "0" + d) : null;
  var h = time.getHours();
  h < 10 ? (h = "0" + h) : null;
  var m = time.getMinutes();
  m < 10 ? (m = "0" + m) : null;
  var s = time.getSeconds();
  s < 10 ? (s = "0" + s) : null;
  if (type === 1) {
    return y + "-" + M + "-" + d;
  } else if (type === 2) {
    return h + ":" + m;
  } else if (type === "firstDay") {
    return y + "-" + M + "-01";
  } else if (type === "minutes") {
    return y + "-" + M + "-" + d + " " + h + ":" + m;
  } else {
    return y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;
  }
};
/* 日期计算-默认为加法运算 */
utils.countDate = function (date, num, type = "add",dateType) {
  let diffTime = num * 24 * 60 * 60 * 1000;
  let startDate = new Date(date).valueOf();
  let endDate = null;
  if (type == "add") {
    endDate = startDate + diffTime;
  } else {
    endDate = startDate - diffTime;
  }
  return utils.TimeFormat(endDate, dateType);
};

//获取上个月的日期
utils.getLastMonth = function (type) {
  var time = new Date();
  var year = time.getFullYear();
  var month = time.getMonth();
  if (month == "0") {
    month = 12;
  }
  month < 10 ? (month = "0" + month) : null;
  var day = time.getDate();
  day < 10 ? (day = "0" + day) : null;
  var preSize = new Date(year, month, 0).getDate(); //上月总天数
  if (type === "first") {
    //上个月的第一天
    return year + "-" + month + "-01";
  } else if (type === "last") {
    //上个月的最后一天
    return year + "-" + month + "-" + preSize;
  } else {
    //上个月的今天
    if (preSize < parseInt(day)) {
      //上月总天数<本月日期，比如3月的30日，在2月中没有30,则为本月1日
      return year + "-" + (month + 1) + "-01";
    } else {
      return year + "-" + month + "-" + day;
    }
  }
};
/* 获取时间差 */
utils.getTimeDiffe = function (startTime, endTime) {
  let timeLimit = (endTime - startTime) / 1000 / 60 / 60 / 24;
  return timeLimit.toFixed(2);
};
/* 更新localStorage */
utils.updateStorage = function () {
  /* 通过localStorage来实现浏览器不同窗口之间的通信 */
  let num = Math.floor(Math.random() * 100000000) + 1; //产生随机数，保证每次的值都不一样
  localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
};

utils.getCurrentTime = function (time) {
  if (time) {
    return new Date(time).getTime();
  } else {
    return new Date().getTime();
  }
};

utils.getYear = function () {
  return new Date().getFullYear().toString();
};
utils.getYearMonth = function () {
  let res = new Date().getMonth() + 1;
  return `${new Date().getFullYear().toString()}-${
    res < 10 ? "0" + res : new Date().getMonth() + 1 + ""
  }`;
};
utils.isNumber = function (value) {
  return typeof value === "number" && !isNaN(value);
};
(utils.getOptionData = function (
  nameStr,
  idStr,
  userType = null,
  orgId = null,
  orgName = null
) {
  let option = [];
  let nameArr = nameStr == null ? [] : nameStr.split(",");
  let idArr = idStr == null ? [] : idStr.split(",");
  let userTypeArr = userType == null ? [] : userType.split(",");
  let orgArr = orgId == null ? [] : orgId.split(",");
  let orgNameArr = orgName == null ? [] : orgName.split(",");
  nameArr.map((i, index) => {
    let item = {
      label: i,
      value: idArr[index],
      isOutOrg: userTypeArr[index],
      orgName: orgNameArr[index],
      orgId: orgArr[index],
    };
    option.push(item);
  });
  return option;
}),
  (utils.changeType = function (type = []) {
    let isOut = [];
    type.map((i) => {
      switch (i) {
        case "employee":
          isOut.push("0");
          break; //本单位
        case "outsource":
          isOut.push("1");
          break; //外单位
        case "temp":
          isOut.push("-1");
          break; //外单位
      }
    });
    return isOut;
  }),
  (utils.convert_tree_data = function (data) {
    data = JSON.parse(JSON.stringify(data));
    for (var i = 0; i < data.length; i++) {
      if (data[i].children != undefined) {
        var temp = data[i].children;
        // 删除孩子节点
        delete data[i].children;
        // 孩子节点加入数组末尾
        for (var j = 0; j < temp.length; j++) {
          data.push(temp[j]);
        }
      }
    }

    return data;
  });
utils.changeUserType = function (data, type) {
  if (type == "code") {
    if (data == "employee") {
      return "0";
    } else if (data == "outsource") {
      return "1";
    } else if (data == "temp") {
      return "-1";
    }
  } else {
    if (data == "0") {
      return "employee";
    } else if (data == "1") {
      return "outsource";
    } else if (data == "-1") {
      return "temp";
    }
  }
};
// 增加金额千分符 会在整数后添加两个0（将表格数据用千分符隔开)
utils.stateFormat = function (row, column, cellValue) {
  if (cellValue) {
    return Number(cellValue)
      .toFixed(2)
      .replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
        return $1 + ",";
      })
      .replace(/\.$/, "");
  }
};
// 去掉金额千分符
utils.delcommafy = function (num) {
  if (!num) return num;
  num = num.toString();
  num = num.replace(/,/gi, "");
  return num;
};
//将输入框的内容，转换成用千分位分隔的数值
utils.changeThousands = function (value) {
  value = value.replace(/[^\d.]/g, ""); // 清除"数字"和"."以外的字符
  value = value.replace(/^\./g, ""); // 验证第一个字符是数字而不是.
  value = value.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); // 保证.只出现一次，而不能出现两次以上
  value = (+value).toFixed(2); // 只能输入两个小数
  let left = this.formatNumber(value.split(".")[0]),
    right = value.split(".")[1];
  value = left + "." + right;
  return value;
};
// 数值三位以，隔开
utils.formatNumber = function (n) {
  var b = parseInt(n).toString();
  var len = b.length;
  if (len <= 3) {
    return b;
  }
  var r = len % 3;
  return r > 0
    ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",")
    : b.slice(r, len).match(/\d{3}/g).join(",");
};
/**遍历数据成树 */

utils.getTrees = function (list, parentId, idKey, pidKey, parentNameKey) {
  let items = {};
  // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
  for (let i = 0; i < list.length; i++) {
    let key = list[i][pidKey];
    if (items[key]) {
      items[key].push(list[i]);
    } else {
      items[key] = [];
      items[key].push(list[i]);
    }
  }
  return utils.formatTree(items, parentId, idKey, parentNameKey);
};

utils.formatTree = function (items, parentId, idKey, parentNameKey) {
  let result = [];
  if (!items[parentId]) {
    return result;
  }
  for (let t of items[parentId]) {
    let sub = utils.formatTree(items, t[idKey], idKey);
    if (sub.length > 0) {
      sub.forEach((i) => {
        i.parentName = t[parentNameKey];
      });
      t.children = sub;
    }
    result.push(t);
  }
  return result;
};

/**
 * 图片转成base64
 * @method
 * @param {String} imgURL
 * @return {String} dataURL
 */
utils.getBase64Image = function (url, callback) {
  var canvas = document.createElement("CANVAS");
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.crossOrigin = "Anonymous";
  img.src = url;
  img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    // var dataURL = canvas.toDataURL();
    var dataURL = canvas.toDataURL("image/" + ext);
    var num = dataURL.indexOf(",");
    dataURL = dataURL.substring(num + 1);
    callback.call(this, dataURL);
    canvas = null;
  };
};

/**
 * 参数拼接
 * */
utils.jointParameter = function (data) {
  var str = "?";
  for (let i in data) {
    let j = data[i];
    if (j && (j + "").trim() !== "") {
      str += i + "=" + j + "&";
    }
  }
  str = str.substring(0, str.length - 1);
  return str;
};

/*
 * 树重组
 * */
utils.dealTreeData = function (data) {
  var parentMask = new Array();
  var root = new Array();

  root.push(data[0]);
  parentMask.push(data[0]);
  data.forEach(function (item, index) {
    if (index == 0) return;
    maskCompare(item);
  });

  function maskCompare(item) {
    if (item.parentMask > parentMask[parentMask.length - 1].parentMask) {
      //子节点
      if (!parentMask[parentMask.length - 1]._child)
        parentMask[parentMask.length - 1]._child = new Array();
      parentMask[parentMask.length - 1]._child.push(item);
      parentMask.push(item);
    } else if (
      item.parentMask <= parentMask[parentMask.length - 1].parentMask
    ) {
      parentMask.pop();
      maskCompare(item);
    }
  }
  return root;
};
//编码
utils.enpathParams = function (data) {
  return encodeURIComponent(JSON.stringify(data));
};
//解码
utils.depathParams = function (data) {
  return JSON.parse(decodeURIComponent(data));
};
//文件转base6
utils.fileFormatBase64 = function (file) {
  return new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      if (e.target.result) {
        resolve(e.target.result);
      } else {
        reject("解析失败，请检查文件是否传入");
      }
    };
  });
};

utils.isPrimitive = function(value) {
  return (
      typeof value === 'string' ||
      typeof value === 'number' ||
      typeof value === 'undefined' ||
      typeof value === 'symbol'
  );
}

// params参数对象转成url
utils.convertObjectToQueryString = function(params, parentKey = '') {
  return Object.entries(params).filter(([_, value]) => {
    let flag = false
    // 数组且不为空
    if(Array.isArray(value) && value.length) {
      flag = true
    }
    // 对象且不为空
    else if(Object.prototype.toString.call(value) === '[object Object]' && Object.keys(value).length) {
      flag = true
    }
    // 布尔值
    else if(typeof value === 'boolean') {
      flag = true
    }
    // 原始值且不为空
    else if(value && utils.isPrimitive(value)) {
      flag = true
    }
    return flag
  }).map(([key, value]) => {
    let nestKey = !parentKey ? key : (Array.isArray(params) ? `${parentKey}[${key}]` : `${parentKey}.${key}`)
    if (typeof value === 'object' && value !== null) {
      return utils.convertObjectToQueryString(value, nestKey)
    } else {
      return `${encodeURIComponent(nestKey)}=${encodeURIComponent(value)}`
    }
  }).join("&")
}

//图片下载
utils.downloadIamge = function (imgsrc, name) {
  //下载图片地址和图片名
  var image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

    var a = document.createElement("a"); // 生成一个a元素
    var event = new MouseEvent("click"); // 创建一个单击事件
    a.download = name || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = imgsrc;
};
/**文件下载并改名 */
utils.downloadFile = function (id, fileName, path, params) {
  let loadingInstance = Loading.service({
    target: ".middleContainer",
    lock: true,
    background: "rgba(255, 255, 255, 0.5)",
  });
  let url = "";
  if(path && params) {
    let paramsUrl = utils.convertObjectToQueryString(params)
    url = `${process.env.VUE_APP_BASEURL}/${path}?${paramsUrl}`
  } else if (path) {
    url = `${process.env.VUE_APP_BASEURL}/${path}`;
  } else {
    url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/preview?fileId=${id}`;
  }
  let token = "";
  if (localStorage.getItem("GDH_WATER_TOKEN")) {
    token = localStorage.getItem("GDH_WATER_TOKEN");
  } else {
    token = process.env.VUE_APP_TOKEN;
  }
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.setRequestHeader("jwt_token", token);
  xhr.setRequestHeader("DYNAMIC_DATA_SOURCE", localStorage.getItem("currDs"));
  xhr.send();
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status === 200) {
      let blob = this.response;
      let name;
      if (xhr.getResponseHeader("content-disposition")) {
        let temp = xhr
          .getResponseHeader("content-disposition")
          .split(";")[1]
          .split("filename=")[1];
        name = decodeURIComponent(temp);
      }
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = fileName || name;
        a.click(); //点击触发下载
        window.URL.revokeObjectURL(url); //下载完成进行释放
        document.body.removeChild(a);
      };
    }
    loadingInstance.close();
  };
};
/**文件下载并改名 */
utils.downloadFileGet = function (id, fileName, path, params) {
  let loadingInstance = Loading.service({
    target: ".middleContainer",
    lock: true,
    background: "rgba(255, 255, 255, 0.5)",
  });
  let url = "";
  if (path) {
    url = `${process.env.VUE_APP_BASEURL}/${path}`;
  } else {
    url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/preview?fileId=${id}`;
  }
  let token = "";
  if (localStorage.getItem("GDH_WATER_TOKEN")) {
    token = localStorage.getItem("GDH_WATER_TOKEN");
  } else {
    token = process.env.VUE_APP_TOKEN;
  }
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.setRequestHeader("jwt_token", token);
  xhr.setRequestHeader("DYNAMIC_DATA_SOURCE", localStorage.getItem("currDs"));
  xhr.send(JSON.stringify(params));
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status === 200) {
      let blob = this.response;
      let name;
      if (xhr.getResponseHeader("content-disposition")) {
        let temp = xhr
          .getResponseHeader("content-disposition")
          .split(";")[1]
          .split("filename=")[1];
        name = decodeURIComponent(temp);
      }
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = fileName || name;
        a.click(); //点击触发下载
        window.URL.revokeObjectURL(url); //下载完成进行释放
        document.body.removeChild(a);
      };
    }
    loadingInstance.close();
  };
};
/**文件下载并改名 */
utils.downloadFilePost = function (id, fileName, path, params) {
  let loadingInstance = Loading.service({
    target: ".middleContainer",
    lock: true,
    background: "rgba(255, 255, 255, 0.5)",
  });
  let url = "";
  if (path) {
    url = `${process.env.VUE_APP_BASEURL}/${path}`;
  } else {
    url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/preview?fileId=${id}`;
  }
  let token = "";
  if (localStorage.getItem("GDH_WATER_TOKEN")) {
    token = localStorage.getItem("GDH_WATER_TOKEN");
  } else {
    token = process.env.VUE_APP_TOKEN;
  }
  let xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.setRequestHeader("jwt_token", token);
  xhr.setRequestHeader("DYNAMIC_DATA_SOURCE", localStorage.getItem("currDs"));
  xhr.send(JSON.stringify(params));
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status === 200) {
      let blob = this.response;
      let name;
      if (xhr.getResponseHeader("content-disposition")) {
        let temp = xhr
          .getResponseHeader("content-disposition")
          .split(";")[1]
          .split("filename=")[1];
        name = decodeURIComponent(temp);
      }
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = fileName || name;
        a.click(); //点击触发下载
        window.URL.revokeObjectURL(url); //下载完成进行释放
        document.body.removeChild(a);
      };
    }
    loadingInstance.close();
  };
};
/**下载压缩文件并改名 */
utils.downloadZipFile = function (
  businessId,
  businessType,
  fileName,
  fileIds,
  path
) {
  let loadingInstance = Loading.service({
    target: ".middleContainer",
    lock: true,
    background: "rgba(255, 255, 255, 0.5)",
  });
  let url = "";
  if (path) {
    url = `${process.env.VUE_APP_BASEURL}/${path}`;
  } else {
    url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/downloadZip?businessId=${businessId}&businessType=${businessType}&fileName=${fileName}&fileIds=${fileIds}`;
  }
  let token = "";
  if (localStorage.getItem("GDH_WATER_TOKEN")) {
    token = localStorage.getItem("GDH_WATER_TOKEN");
  } else {
    token = process.env.VUE_APP_TOKEN;
  }
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.setRequestHeader("jwt_token", token);
  xhr.setRequestHeader("DYNAMIC_DATA_SOURCE", localStorage.getItem("currDs"));
  xhr.send();
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status === 200) {
      let blob = this.response;
      let name;
      if (xhr.getResponseHeader("content-disposition")) {
        let temp = xhr
          .getResponseHeader("content-disposition")
          .split(";")[1]
          .split("filename=")[1];
        name = decodeURIComponent(temp);
      }
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = fileName || name;
        a.click(); //点击触发下载
        window.URL.revokeObjectURL(url); //下载完成进行释放
        document.body.removeChild(a);
      };
    }
    loadingInstance.close();
  };
};
/**视频回显展示 */
utils.echoVideo = function (id, path, database) {
  return new Promise((resolve, reject) => {
    let url = "";
    let currDs = database ? database : "_default";
    if (path) {
      url = `${process.env.VUE_APP_BASEURL}/${path}`;
    } else {
      url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/preview?currDs=${currDs}&fileId=${id}`;
    }
    let token = "";
    if (localStorage.getItem("GDH_WATER_TOKEN")) {
      token = localStorage.getItem("GDH_WATER_TOKEN");
    } else {
      token = process.env.VUE_APP_TOKEN;
    }
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("jwt_token", token);
    xhr.send();
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        const src = URL.createObjectURL(this.response);
        resolve(src);
      }
    };
  });
};
/**图片回显展示 */
utils.echoImg = function (id, path, database) {
  return new Promise((resolve, reject) => {
    let url = "";
    let currDs = database ? database : "_default";
    if (path) {
      url = `${process.env.VUE_APP_BASEURL}/${path}`;
    } else {
      url = `${process.env.VUE_APP_BASEURL}/eam-common-web/attachment/preview?currDs=${currDs}&fileId=${id}`;
    }
    let token = "";
    if (localStorage.getItem("GDH_WATER_TOKEN")) {
      token = localStorage.getItem("GDH_WATER_TOKEN");
    } else {
      token = process.env.VUE_APP_TOKEN;
    }
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("jwt_token", token);
    xhr.send();
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        let blob = this.response;
        utils.blobToBase64(blob, (res) => {
          resolve(res);
        });
      }
    };
  });
};
//将blob数据转换为base64
utils.blobToBase64 = function (blob, callback) {
  let a = new FileReader();
  a.onload = function (e) {
    callback(e.target.result);
  };
  a.readAsDataURL(blob);
};
//传el-table的‘ref‘，table转excel
utils.tableToExcel = function (el, name) {
  let table = el.childNodes[1].childNodes[0];
  let body = el.childNodes[2].childNodes[0];
  if (false) {
    var idTmr;
    var uri = "data:application/vnd.ms-excel;base64,",
      template =
        '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
      base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
      },
      format = function (s, c) {
        return s.replace(/{(\w+)}/g, function (m, p) {
          return c[p];
        });
      };
    if (!table.nodeType) table = document.getElementById(table);
    var ctx = {
      worksheet: name || "Worksheet",
      table: table.innerHTML,
    };
    window.location.href = uri + base64(format(template, ctx));
  }
  return table.innerHTML + body.childNodes[1].innerHTML;
};
//后台返回二进制，进行blob，前提‘请求类型必须为blob’
utils.resultFileBlob = function (res, name = "数据导出报表", ext = ".xlsx") {
  let blob = new Blob([res], {
    type: "application/vnd.ms-excel",
  });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, `${name}.${ext}`);
  } else {
    let blobUrl = window.URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.download = `${name}.${ext}`;
    a.href = blobUrl;
    a.click();
  }
};

/**全屏控制 */
utils.fullScreenFun = function (iFullscreen) {
  // var iFullscreen = false; //当前是否全屏状态
  var fullscreenEnabled =
    document.fullscreenEnabled ||
    document.mozFullScreenEnabled ||
    document.webkitFullscreenEnabled ||
    document.msFullscreenEnabled;

  if (fullscreenEnabled) {
    let de = document.documentElement;
    if (iFullscreen) {
      //关闭全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      }
    } else {
      //打开全屏
      if (de.requestFullscreen) {
        de.requestFullscreen();
      } else if (de.mozRequestFullScreen) {
        de.mozRequestFullScreen();
      } else if (de.webkitRequestFullScreen) {
        de.webkitRequestFullScreen();
      }
    }
  } else {
    alert("浏览器当前不能全屏");
  }
};
/**
 * 判断对象的属性是否有空
 */
utils.objIsNull = function (obj) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] === "") {
        return true;
      } else {
        return false;
      }
    }
  }
};
utils.getEquipmentParams = function (form) {
  let data = {};
  getPresetParamsApi(form).then((res) => {
    data = res.data || {};
  });
  return data;
};
//判断是否安装了控件
utils.isInstallPrintSoftware = function (path) {
  let loadingInstance = Loading.service({
    target: ".middleContainer",
    lock: true,
    background: "rgba(255, 255, 255, 0.5)",
  });
  let win = window.open(path, "_blank");
  setTimeout(() => {
    win.close();
  }, 2000);
  loadingInstance.close();
};
//获取用户电脑ip
utils.getIp = () => {
  let IP = "";
  let token = "";
  if (localStorage.getItem("GDH_WATER_TOKEN")) {
    token = localStorage.getItem("GDH_WATER_TOKEN");
  } else {
    token = process.env.VUE_APP_TOKEN;
  }
  $.ajax({
    url: `${process.env.VUE_APP_BASEURL}/eam-common-web/printConfig/getIp`,
    type: "get",
    async: false,
    headers: {
      jwt_token: token,
    },
    success: (res) => {
      IP = res.data;
    },
  });
  return IP;
};
//判断用户是否有业务权限
utils.getJurisdiction = function (data, code) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].code == code) {
      return data[i].jurisdiction;
    }
  }
  return true;
};
//按钮禁用提示
utils.getJurisdictionContent = function (data, code, role) {
  if (role || role == undefined) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].code == code && !data[i].jurisdiction) {
        return data[i].rule;
      }
    }
    return null;
  } else {
    return "未授权功能";
  }
};
//判断用户是否符合岗位
utils.isPosition = async function (account, position, appId) {
  let flag = false;
  await getUserDataByAccount(account)
    .then((res) => {
      if (res.data) {
        let index = -1;
        let outIndex = -1;
        if (res.data.postUserVoList) {
          index = res.data.postUserVoList.findIndex((item) => {
            return item.appId == appId && item.postName == position;
          });
        }
        if (res.data.orgVoList) {
          outIndex = res.data.orgVoList.findIndex((item) => {
            return item.appId == appId && item.outOrg == "1";
          });
        }
        if (index != -1 || outIndex != -1) {
          flag = true;
        } else {
          flag = false;
        }
      } else {
        flag = false;
      }
    })
    .catch((e) => {
      flag = false;
    });
  return flag;
};

utils.qqMap = function () {
  return new Promise(function (resolve, reject) {
    window.init = function () {
      resolve();
    };
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src =
      "https://map.qq.com/api/gljs?v=1.exp&key=LDJBZ-JSFCX-2PE4O-TUXJ6-UR7U3-I3FD5&callback=init";
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

export default utils;
